// 自定义指令
import Vue from 'vue'

//为空显示--
Vue.filter("empty", value => {
  value = trimRight(trimLeft(value));
  if (
    value === "" ||
    JSON.stringify(value) === "undefined" ||
    JSON.stringify(value) === "null" ||
    JSON.stringify(value) === "NaN"
  ) return "--";
  return value;

  function trimLeft(s) {
    if (s == null) {
      return "";
    }
    var whitespace = new String(" \t\n\r");
    var str = new String(s);
    if (whitespace.indexOf(str.charAt(0)) != -1) {
      var j = 0,
        i = str.length;
      while (j < i && whitespace.indexOf(str.charAt(j)) != -1) {
        j++;
      }
      str = str.substring(j, i);
    }
    return str;
  }

  //去掉右边的空白 www.2cto.com   
  function trimRight(s) {
    if (s == null) return "";
    var whitespace = new String(" \t\n\r");
    var str = new String(s);
    if (whitespace.indexOf(str.charAt(str.length - 1)) != -1) {
      var i = str.length - 1;
      while (i >= 0 && whitespace.indexOf(str.charAt(i)) != -1) {
        i--;
      }
      str = str.substring(0, i + 1);
    }
    return str;
  }
})

//数字格式化
Vue.filter('number', (value, fixed) => {
  let reg = /^[+-]?[\d]+([.][\d]*)?([Ee][+-]?[\d]+)?$/;
  if (!reg.test(value)) return "0";
  if (isNaN(fixed)) fixed = 0;
  value = getFullNum(value);
  value = getThousandNumber(value, fixed);
  return value;

  function getFullNum(num) {
    //处理非数字
    if (isNaN(num)) {
      return num
    };
    //处理不需要转换的数字
    let str = '' + num;
    str = str.toLocaleLowerCase();
    if (!/e/i.test(str)) {
      return num;
    };
    //判断正负
    let number = str.split("e")[0];
    let symbol = str.split("e")[1];
    // console.log(str,number,symbol)
    // //先获取到精确的小数位
    let fixed = ('' + num).match(/\d+$/)[0];
    if (parseInt(symbol) < 0) {
      let cc = 1;
      if (number.indexOf(".") > -1) {
        cc = number.split(".")[1].length;
      } else {
        cc = number.length;
      }
      return new Number(num).toFixed(parseInt(fixed) + cc);
    } else {
      return new Number(num).toFixed(0);
    }
  }

  function getThousandNumber(number, fixed) {
    number = parseFloat(number).toFixed(fixed)
    let num = number;
    let points = "";
    if (number.indexOf(".") > -1) {
      num = number.split(".")[0];
      points = number.split(".")[1];
    }
    let counter = 0;
    let result = "";
    for (var i = num.length - 1; i >= 0; i--) {
      counter++;
      result = num.charAt(i) + result;
      if (!(counter % 3) && i != 0) {
        result = ',' + result;
      }
    }
    if (points != "") {
      return result + "." + points;
    } else {
      return result;
    }
  }
})

Vue.filter('numberf', function (value, fixed = 2) {
  let reg = /^[+-]?[\d]+([.][\d]*)?([Ee][+-]?[\d]+)?$/;
  if (!reg.test(value)) return 0;
  let resut = Number(parseFloat(value).toFixed(fixed));
  return resut;
})

// 数字加千分位符号
Vue.filter('currencyKb', function (num) {
  if (num) {
    num = num.toString().replace(/\$|\,/g, '');
    if (isNaN(num))
      num = "0";
    let sign = (num == (num = Math.abs(num)));
    num = Math.floor(num * 100 + 0.50000000001);
    let cents = num % 100;
    num = Math.floor(num / 100).toString();
    if (cents < 10)
      cents = "0" + cents;
    for (var i = 0; i < Math.floor((num.length - (1 + i)) / 3); i++)
      num = num.substring(0, num.length - (4 * i + 3)) + ',' +
        num.substring(num.length - (4 * i + 3));
    return (((sign) ? '' : '-') + num + '.' + cents);
  }
});

Vue.filter('currencyWy', function (num, type) {
  if (type == 'number') {
    return Number((num / 10000).toFixed(4)) + " 万元"
  }
  if (num) {
    return Number((num / 10000).toFixed(4)) + " 万元"
  } else {
    return "0 万元"
  }
});

//百分数
Vue.filter('percent', (value, multiple, fixed) => {
  let reg = /^[+-]?[\d]+([.][\d]*)?([Ee][+-]?[\d]+)?$/;
  if (!reg.test(value)) return value;
  if (isNaN(fixed)) fixed = 2;
  if (isNaN(multiple)) multiple = 1;
  value = multiple * value;
  value = Vue.filter("number")(value, fixed);
  return Number(value) + "%";
})

//首字大写
Vue.filter('capitalize', (value) => {
  var i, ss = value.toLowerCase().split(/\s+/);
  for (i = 0; i < ss.length; i++) {
    ss[i] = ss[i].slice(0, 1).toUpperCase() + ss[i].slice(1);
  }
  return ss.join(' ');
})

//字母大写
Vue.filter('uppercase', (value) => {
  return value.toUpperCase();
})

//字母小写
Vue.filter('lowercase', (value) => {
  return value.toLowerCase();
})

//查询身份证性别
Vue.filter('sex', (value) => {
  var name = "";
  switch (value) {
    case 0: name = "--"; break;
    case 1: name = "男"; break;
    case 2: name = "女"; break;
    default: name = "";
  }
  return name;
})

//根据身份证获取年龄
Vue.filter('age', (value) => {
  if (!value) {
    return "";
  }
  //获取年龄
  var myDate = new Date();
  var month = myDate.getMonth() + 1;
  var day = myDate.getDate();
  var age = myDate.getFullYear() - value.substring(6, 10) - 1;
  if (value.substring(10, 12) < month || value.substring(10, 12) == month && value.substring(12, 14) <= day) {
    age++;
  }
  return age;
})

//platfrom
Vue.filter('platform', (value) => {
  var platform = "";
  switch (value) {
    case "ms": platform = "管理端"; break;
    case "pc": platform = "客户端"; break;
    case "mb": platform = "手机端"; break;
    default: platform = "其他";
  }
  return platform;
})

//时间转换
Vue.filter('date', (date, format, isMoment) => {
  if (!date) return "--";
  if (!format) format = "yyyy-MM-dd HH:mm:ss";
  // if ((date + "").indexOf("T") > 0) {
  //   isMoment = true;
  // }
  var tagNum = /^[0-9]*$/.test(date)
  if (!tagNum && date.indexOf("T") < 0) {
    date = date.replace(/-/g, "/");
  }
  if (tagNum || Date.parse(date)) {
    if (tagNum) date = parseInt(date);
    date = new Date(date).getTime();
    if (date.toString().length == 10) {
      date = date * 1000;
    }
    let offest = new Date().getTimezoneOffset();
    if (isMoment) date = date - offest * 1000 * 60;
    let datetime = dateFtt(format, date);
    return datetime;
  } else {
    return date;
  }
  /**************************************时间格式化处理************************************/
  function dateFtt(fmt, date) { //author: meizz   
    var date = new Date(date);
    var o = {
      "M+": date.getMonth() + 1, //月份   
      "d+": date.getDate(), //日   
      "H+": date.getHours(), //小时   
      "m+": date.getMinutes(), //分   
      "s+": date.getSeconds(), //秒   
      "q+": Math.floor((date.getMonth() + 3) / 3), //季度   
      "S": date.getMilliseconds() //毫秒   
    };
    if (/(y+)/.test(fmt))
      fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
      if (new RegExp("(" + k + ")").test(fmt))
        fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
  }

})

//depType
Vue.filter('week', (value) => {
  var arr = ["日", "一", "二", "三", "四", "五", "六"];
  var weekNum = 0;
  if (value) {
    weekNum = new Date(value).getDay();
  } else {
    weekNum = new Date().getDay();
  }
  return "星期" + arr[weekNum];
})

//depType
Vue.filter('depType', (value) => {
  var platform = "";
  switch (value) {
    case 1: platform = "行政部门"; break;
    case 2: platform = "教学部门"; break;
    default: platform = "其他";
  }
  return platform;
})


//arrstring
Vue.filter('arrstring', (arr, key, link) => {
  var str = "";
  arr.map((item, index) => {
    if (index == arr.length - 1) {
      str += item[key];
    } else {
      str += item[key] + link;
    }
  })
  return str;
})

//图片重置尺寸
Vue.filter('resize', (url, w, h) => {
  return `${url}?x-oss-process=image/resize,w_${w},h_${h}`
})

Vue.filter('fileView', (path, server) => {
  if (!path) {
    return "";
  }
  if (server == "own") {
    return 'http://47.115.75.110:8012/onlinePreview?url=' + Base64.encode(path);
  } else {
    let target = ['.doc', '.xls', '.ppt'].find(item => path.indexOf(item) > 0);
    if (target) {
      return "https://view.officeapps.live.com/op/view.aspx?src=" + encodeURIComponent(path);
    } else {
      return path;
    }
  }
})